package creative.fire.interview.polycom;

/**
 * @author feuyeux@gmail.com 2011-8-4
 */
public class Indexof {

	public int process(char[] src, char[] dest) {
		if (src.length < dest.length)
			return -1;
		if (src.length == 0 || dest.length == 0)
			return 0;
		int index = 0;
		boolean match = false;
		int j = 0;
		for (int i = 0; i < src.length; i++) {
			if (match)
				j++;
			if (src[i] == dest[j]) {
				if (!match) {
					match = true;
					index = i;
				}
				if (j == dest.length - 1)
					return index;
			} else {
				if (src.length - 1 == i)
					return -1;
				i = index;
				index = -1;
				j = 0;
				match = false;
			}
		}

		return -1;
	}

	public int jdkIndexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount,
			int fromIndex) {
		if (fromIndex >= sourceCount) {
			return (targetCount == 0 ? sourceCount : -1);
		}
		if (fromIndex < 0) {
			fromIndex = 0;
		}
		if (targetCount == 0) {
			return fromIndex;
		}

		char first = target[targetOffset];
		int max = sourceOffset + (sourceCount - targetCount);

		for (int i = sourceOffset + fromIndex; i <= max; i++) {
			/* Look for first character. */
			if (source[i] != first) {
				while (++i <= max && source[i] != first)
					;
			}

			/* Found first character, now look at the rest of v2 */
			if (i <= max) {
				int j = i + 1;
				int end = j + targetCount - 1;
				for (int k = targetOffset + 1; j < end && source[j] == target[k]; j++, k++)
					;

				if (j == end) {
					/* Found whole string. */
					return i - sourceOffset;
				}
			}
		}
		return -1;
	}

	public static void main(String[] args) {
		String s1 = "caab";
		String s4 = "baab";
		String s2 = "aab";
		String s3 = "ab";
		String s5 = "";
		String s6 = "aaaaaaa";

		String d1 = "ab";
		String d2 = "aaaaaaa";
		String d3 = "";

		Indexof me = new Indexof();
		System.out.println(s1.indexOf(d1) + " ? " + me.process(s1.toCharArray(), d1.toCharArray()));
		System.out.println(s2.indexOf(d1) + " ? " + me.process(s2.toCharArray(), d1.toCharArray()));
		System.out.println(s3.indexOf(d1) + " ? " + me.process(s3.toCharArray(), d1.toCharArray()));
		System.out.println(s4.indexOf(d1) + " ? " + me.process(s4.toCharArray(), d1.toCharArray()));
		System.out.println(s5.indexOf(d1) + " ? " + me.process(s5.toCharArray(), d1.toCharArray()));
		System.out.println(s5.indexOf(d3) + " ? " + me.process(s5.toCharArray(), d3.toCharArray()));
		System.out.println(s6.indexOf(d1) + " ? " + me.process(s6.toCharArray(), d1.toCharArray()));
		System.out.println(s1.indexOf(d2) + " ? " + me.process(s1.toCharArray(), d2.toCharArray()));
		System.out.println(s1.indexOf(d3) + " ? " + me.process(s1.toCharArray(), d3.toCharArray()));
	}
}
